﻿using MiserBlogHelper;
using System;
using System.Collections.Generic;
using MiserDB.DataHelp;

using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Web;
using System.Collections;
using System.Xml.XPath;

namespace MiserBlogData.Entities
{
    public class A_Person
    {
        protected readonly static string _cookieStr = "miserblog_person";
        protected readonly static string _cookieP = "p";
        protected readonly static string _cookiePName = "pName";
        protected readonly static string _cookiePEmail = "pEmail";


        protected readonly static System.Collections.Generic.Dictionary<Type.CookieParms, string> _cookieParmsDic = new System.Collections.Generic.Dictionary<MiserBlogData.Entities.Type.CookieParms, string>();

        public System.Web.HttpCookie _cookie = new System.Web.HttpCookie(_cookieStr);

        public A_Person()
        {
            Name = "匿名";
        }

        static A_Person()
        {
            _cookieParmsDic.Add(MiserBlogData.Entities.Type.CookieParms.Pid, "pId");
            _cookieParmsDic.Add(MiserBlogData.Entities.Type.CookieParms.Time, "time");
            _cookieParmsDic.Add(MiserBlogData.Entities.Type.CookieParms.Role, "role");
            _cookieParmsDic.Add(MiserBlogData.Entities.Type.CookieParms.IP, "ip");
        }

        public virtual int Id { set; get; }

        public virtual string Email { set; get; }
        public virtual string Name { set; get; }
        public virtual string Pwd { set; get; }
        public virtual DateTime CDate { set; get; }
        public virtual short State { set; get; }
        public virtual string IP { set; get; }
        public virtual short Role { set; get; }
        public virtual DateTime UDate { set; get; }
        public virtual string Face { set; get; }
        public virtual int ArticleNum { set; get; }
        public virtual IList<Comment> CommentList { set; get; }


        public static string CookieStr { get { return _cookieStr; } }
        public static string CookieP { get { return _cookieP; } }
        public static string CookiePName { get { return _cookiePName; } }
        public static System.Collections.Generic.Dictionary<Type.CookieParms, string> CookieParmsDic { get { return _cookieParmsDic; } }

        /// <summary>
        /// 创建website浏览用户
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="UserName"></param>
        /// <param name="Pwd"></param>
        /// <returns></returns>
        public T Verify<T>() where T : class
        {
            if (string.IsNullOrEmpty(this.Name) || string.IsNullOrEmpty(this.Pwd))
            {
                return null;
            }
            //this.Pwd = 
            MiserDB.DataHelp.PersonHelper p = new MiserDB.DataHelp.PersonHelper();
            return p.VerifyData<T>(this.Name, this.Pwd);
        }

        /// <summary>
        /// 根据cookie创建一个用户对象
        /// </summary>
        /// <returns></returns>
        public static A_Person CreateWithCookie()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            System.Web.HttpCookie cookie = context.Request.Cookies[A_Person.CookieStr];

            int uid = 0;
            short role = (short)PersonRole.Anonymity;
            string userName = string.Empty;

            if (cookie != null)
            {
                string p = cookie[A_Person.CookieP];
                if (!string.IsNullOrEmpty(p))
                {
                    string pValue = MiserBlogHelper.Helper.StrHelper.Decrypt(p);
                    string[] oneArray = pValue.Split('&');

                    if (oneArray.Length == A_Person.CookieParmsDic.Count)
                    {
                        foreach (var s1 in oneArray)
                        {
                            string[] twoArray = s1.Split('=');
                            if (twoArray.Length == 2)
                            {
                                #region
                                if (twoArray[0] == A_Person.CookieParmsDic[MiserBlogData.Entities.Type.CookieParms.Pid])
                                {
                                    if (!int.TryParse(twoArray[1], out uid))
                                    {
                                        break;
                                    }
                                }
                                else if (twoArray[0] == A_Person.CookieParmsDic[MiserBlogData.Entities.Type.CookieParms.Role])
                                {
                                    if (!short.TryParse(twoArray[1], out role))
                                    {
                                        break;
                                    }
                                }
                                    //时间戳检验
                                else if (twoArray[0] == A_Person.CookieParmsDic[MiserBlogData.Entities.Type.CookieParms.Time])
                                {
                                    if (MiserBlogHelper.Helper.TimeHelper.CompareTo(DateTime.Now, twoArray[1]) <= 0)
                                    {
                                        break;
                                    }
                                }
                                else if (twoArray[0] == A_Person.CookieParmsDic[MiserBlogData.Entities.Type.CookieParms.IP])
                                {
                                    if (!MiserBlogHelper.Helper.HttpHelper.CompareTo(twoArray[1]))
                                    {
                                        role = (int)PersonRole.Anonymity;
                                        break;
                                    }
                                }
                                //else if (twoArray[0] == A_Person.CookieParmsDic[MiserBlogData.Entities.Type.CookieParms.PName])
                                //{
                                //    if (string.IsNullOrEmpty(twoArray[1]))
                                //    {
                                //        break;
                                //    }
                                //    else
                                //    {
                                //        userName = twoArray[1];
                                //    }
                                //}
                                else { break; }
                                #endregion
                            }
                            else { break; }
                        }
                    }
                }
            }
            A_Person person = PersonFactory(role);
            if (person == null) { return null; }

            if (role != (short)PersonRole.Anonymity && !string.IsNullOrEmpty(cookie[A_Person.CookiePName]))
            {
                person.Name = cookie[_cookiePName];
                person.Email = cookie[_cookiePEmail];
            }
            person.Role = role;
            person.Id = uid;

            return person;
        }

        /// <summary>
        /// 通过角色值 创建不同的人对象
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        protected static A_Person PersonFactory(short role)
        {
            PersonRole pr = (PersonRole)role;
            switch (pr)
            {
                case PersonRole.UserVIP: return new UserVIP();
                case PersonRole.Anonymity: return new A_Person();
                case PersonRole.Visitor: return new Visitor();
                default: return null;
            }
        }

        /// <summary>
        /// 创建cookie
        /// </summary>
        /// <param name="cookieDayTime"></param>
        /// <returns></returns>
        public virtual bool CreateCookie(int cookieDayTime)
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            if (context.Request.Browser.Cookies)
            {
                //明文 用户名 
                //密文 用户id 时间戳 ip地址 用户的角色
                this.IP = MiserBlogHelper.Helper.HttpHelper.GetIP();
                DateTime time = DateTime.Now.AddDays(cookieDayTime);
                string dataBag = string.Empty;//需要加密的数据包

                System.Text.StringBuilder dataSB = new System.Text.StringBuilder();
                dataSB.Append("pId=");
                dataSB.Append(this.Id);
                dataSB.Append("&time=");
                dataSB.Append(time.Year);
                dataSB.Append("-");
                dataSB.Append(time.Month);
                dataSB.Append("-");
                dataSB.Append(time.Day);
                dataSB.Append(" ");
                dataSB.Append(time.Hour);
                dataSB.Append(":");
                dataSB.Append(time.Minute);
                dataSB.Append(":");
                dataSB.Append(time.Second);
                dataSB.Append("&role=");
                dataSB.Append(this.Role);
                dataSB.Append("&ip=");
                dataSB.Append(this.IP);

                dataBag = dataSB.ToString();

                dataBag = MiserBlogHelper.Helper.StrHelper.Encrypt(dataBag);

                _cookie[_cookiePName] = this.Name;
                _cookie[_cookieP] = dataBag;
                _cookie[_cookiePEmail] = this.Email;
                if (cookieDayTime != 0)
                {
                    _cookie.Expires = time;
                }
                System.Web.HttpResponse respones = context.Response;
                respones.Cookies.Add(_cookie);
            }
            return false;
        }


        /// <summary>
        /// 得到用户头像
        /// </summary>
        /// <param name="person"></param>
        /// <returns></returns>
        public static string GetPersonFace(A_Person person)
        {

            if (person == null) return string.Empty;
            
            if (person.Role == (short)PersonRole.Anonymity)
            {
                
                string imgPath = System.Configuration.ConfigurationManager.AppSettings["connString"];
                return imgPath + person.Face;
            }
            else
            {
                string facePath = System.Configuration.ConfigurationManager.AppSettings["face"];
                return facePath + person.Face;
            }
        }

        //public virtual void AddComment(Comment comment)
        //{
        //    if (CommentList == null) CommentList = new List<Comment>();
        //    if (CommentList.Contains(comment)) return;
        //    CommentList.Add(comment);
        //    comment.User = this;
        //}

        public static T GetUser<T>(int userId) where T : class
        {
            PersonHelper ph = new PersonHelper();
            return ph.GetData<T>(userId);

        }
    }
}
